const chreeio = require('cheerio'),
    puppeteer = require('puppeteer');

const rootUrl = 'https://sou.autohome.com.cn/';

class Result {
    constructor() {
        this.name = '',
            this.pic = ''
    }
}

let resList = [];

async function Test(carname) {
	console.log(resList.length);
    // 初始化浏览器
	if(resList.length >0){
		resList = [];
	}
    const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] });
    // const browser = await puppeteer.launch({ headless: false })
    try {
        const page = await browser.newPage();
        await page.goto(rootUrl);
        // let res = await page.content();
        // 获取输入框
        let inputEle = await page.$('.txt-search');
        // 输入框焦点
        await inputEle.focus();
        // 输入车型
        await page.keyboard.type(carname);
        // 获取搜索按钮
        let buttonEle = await page.$('.btn-search');
        // 点击按钮
        await buttonEle.click();
        // 等待路由跳转完毕
        await page.waitForNavigation();
        // 获取网页
        let res = await page.content();
        // 将网页解析
        let $ = chreeio.load(res);
        // 获取那几个车的dd 
        let ddEle = $('.club-box2>dl>dd');
	if(ddEle.length == 0){
		return '无';
	}else{
        for (let i = 0; i < ddEle.length; i++) {
            // 新建对象
            let carinfo = new Result();
            // 获取图片地址
            carinfo.pic = $(ddEle[i]).find('img').attr('src');
            // 获取车名
            carinfo.name = $(ddEle[i]).find('div>a').attr('title');
            // 放入数组
            resList.push(carinfo);
        }
  	//返回数组
	return resList;
	}
    } catch (error) {
        console.log(error);
    }
    // 浏览器关闭
    browser.close();
}

module.exports = { Test }
